<?php


namespace catchAdmin\storehouse\controller;


use catchAdmin\basics\model\Provider;
use catchAdmin\stock\model\WarehouseConfig;
use catchAdmin\storehouse\model\Project as ProjectModel;
use catchAdmin\storehouse\model\ProjectWarehouseConfig;
use catchAdmin\storehouse\model\Tray;
use catcher\base\CatchController;
use catcher\base\CatchRequest as Request;
use catcher\CatchAuth;
use catcher\CatchResponse;
use catcher\library\client\Response;
use think\Exception;
use think\facade\Db;
class Project extends CatchController
{
    protected $project;

    public function __construct(ProjectModel $project)
    {
        $this->project = $project;
    }

    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function index(CatchAuth $auth)
    {
        $user = $auth->user();
        $list = $this->project->getAttrList($user['tenant_id'],$user['id'],$user['position'],$user['type']);
        return CatchResponse::success($list->toArray(), '查询成功');
    }
    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function project(CatchAuth $auth)
    {
        $user = $auth->user();
        $where=[];
        $where[]=['pid','=',0];
        $where[]=['tenant_id','=',$user['tenant_id']];
        $where[]=['deleted_at','=',0];

        $data = Db::name('db_project')->where($where)->select();
        return CatchResponse::success($data, '查询成功');
    }
    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function getProject(CatchAuth $auth)
    {
        $user = $auth->user();
        $list = $this->project->getAttrList($user['tenant_id'],$user['id'],$user['position'],$user['type']);
        return CatchResponse::success($list->toArray(), $user);
    }
    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function create(CatchAuth $auth,Request $request)
    {
        $params = $request->param();
//        $if_exist = Db::table('db_project')->where('project_name',$params['project_name'])->find();
//        if($if_exist){
//            return CatchResponse::fail('项目名已存在');
//        }
        if(!empty($params['employees'])){
            $params['employees'] = implode(',',$params['employees']);
        }else{
            $params['employees'] = '';
        }
        //$params['employees'] = '';
        $user = $auth->user();
        $params['tenant_id'] = $user['tenant_id'];
        $params['project_id'] = date('YmdHis').rand(1000,9999);
        $params['creator_id']=$user['id'];
        $params['created_at']=time();

        //return $params;

        $check = [];
        $projectWarehouseArr = [];
        if(0 < $params['pid']){//如果是子项目
            //前台传过来的的所有id
//            $config_ids = $params['config_ids'];
            if(!array_key_exists('config_ids',$params) ||  empty ($config_ids = $params['config_ids'])){
                return CatchResponse::fail('没有指定库位');
            }

            $warehouseConfigModel = new WarehouseConfig;
            //2.获取所有新增可用的库位
            $list = $warehouseConfigModel->available();
            $list =  $warehouseConfigModel->typesetting($list);

            $check = $warehouseConfigModel->checkConfig($config_ids,$list);

            //dd($check);
        }else{//父项目
            unset($params['p_name']);
            unset($params['employees']);
        }

        Db::startTrans();
        try {
            unset($params['config_ids']);

            $this->project->storeBy($params);

            foreach ($check as $value){
                $checkArr = explode(',',$value);

                $projectWarehouseArr[] = [
                    'project_pid'=>$params['pid'],
                    'project_id'=> Db::table('db_project')->where('project_id',$params['project_id'])->value('id') ,
                    'config_level_1'=>$checkArr[0],
                    'config_level_2'=>$checkArr[1],
                    'config_level_3'=>$checkArr[2],
                    'tenant_id'=>$params['tenant_id'],
                    'creator_id'=>$params['creator_id']
                ];
            }

            //写入产品对应库位表
            (new ProjectWarehouseConfig)->insertAllBy($projectWarehouseArr);

            Db::commit();
        }catch (\Exception $exception) {
            Db::rollback();
            throw new Exception('项目创建失败' . $exception->getMessage());
        }


        //$this->project->storeBy($params);
        return CatchResponse::success('', '新建成功');
    }
    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function update(CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        $params = $request->param();

        $map=[];
        $map[]=['id','<>',$params['id']];
        $map[]=['pid','=',$params['pid']];
        $map[]=['deleted_at','=',0];
        $map[]=['tenant_id','=',$user['tenant_id']];
        $map[]=['project_name','=',$params['project_name']];
        $if_exist = Db::table('db_project')->where($map)->find();
        if($if_exist){
            return CatchResponse::fail('项目名已存在');
        }
        if(!empty($params['employees'])){
            $params['employees'] = implode(',',$params['employees']);
        }else{
            $params['employees'] = '';
        }
        $id = $params['id'];

        //return $params;

        //  0被过滤了，所以判断是否存在建
        if(!array_key_exists('pid',$params) || 0 == $params['pid']){//说明修改的是父级，只是修改名字
            $this->project->updateBy($id, $params);
            return CatchResponse::success('', '编辑成功');
        }

        //前台传过来的的所有id
        $config_ids = $params['config_ids'];

        if(empty($config_ids)){
            return CatchResponse::fail('没有指定库位');
        }

        $warehouseConfigModel = new WarehouseConfig;
        //2.获取所有新增可用的库位
        $list = $warehouseConfigModel->available();
        $list =  $warehouseConfigModel->typesetting($list);
        $check = $warehouseConfigModel->checkConfig($config_ids,$list);

        $projectWarehouseArr = [];

        Db::startTrans();
        try {

            unset($params['config_ids']);
            $this->project->updateBy($id, $params);


            foreach ($check as $value){
                $checkArr = explode(',',$value);

                $projectWarehouseArr[] = [
                    'project_pid'=> $params['pid'],
                    'project_id'=> $id ,
                    'config_level_1'=>$checkArr[0],
                    'config_level_2'=>$checkArr[1],
                    'config_level_3'=>$checkArr[2],
                    'tenant_id'=>$params['tenant_id'],
                    'creator_id'=>$params['creator_id']
                ];
            }
            //删除原本关系表
            Db::table('db_project_warehouse_config')->where('project_id','=',$id)->delete();

            //写入产品对应库位表
            (new ProjectWarehouseConfig)->insertAllBy($projectWarehouseArr);

            Db::commit();
        }catch (\Exception $exception) {
            Db::rollback();
            throw new Exception('项目创建失败' . $exception->getMessage());
        }

        return CatchResponse::success('', '编辑成功');
    }
    /**
     *
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function delete(Request $request)
    {
        $id = $request->post('id');
         $ids = explode(',',$this->project->get_all_child_cate($id));
         $ids[] = $id;


        Db::startTrans();
        try {
            $res = $this->project->deleteBy($ids);
            //删除项目，释放占用库位
           // return json($ids);
            Db::table('db_project_warehouse_config')->where('project_id','in',$ids)->delete();

            Db::commit();
        }catch (\Exception $exception) {
            Db::rollback();
            throw new Exception('项目删除失败' . $exception->getMessage());
        }


         return CatchResponse::success($res);
    }

    public function warehouse($id=''){
        $warehouseConfigModel = new WarehouseConfig;

        $list = $warehouseConfigModel->available($id);

        $result['all'] = $list;

        if(!empty($id)){//可用+选择
            //获取 所有库位选中
            $result['checked'] = $warehouseConfigModel->getProjectCheckList($id);
        }

        return CatchResponse::success($result);
    }

    //项目客户
    public function provider(CatchAuth $auth){

        $user = $auth->user();
        return CatchResponse::success((new Provider)->getEntrust($user['tenant_id']));
    }

    //项目订单
    public function allOrder(CatchAuth $auth,Request $request){
        $user = $auth->user();
        $warehousingModel = (new \catchAdmin\storehouse\model\Warehousing());
        $params = $request->param();

        //设置默认分页限制
        if(!array_key_exists('page',$params) || !array_key_exists('limit',$params)){
            $params['page'] = 1; $params['limit'] = 10;
        }

        $where = [
            ['deleted_at','=',0],
        ];

        if($user['type'] !== 1 ){
            $where[] = ['tenant_id','=',$user['tenant_id']];
        }

        $warehouse_out_sql = (new \catchAdmin\storehouse\model\WarehouseOut())
            ->field("warehouse_out_id as order_id , IF(ISNULL(warehouse_out_id),0,'出库') as order_type,created_at,goods_number,project_id,project_client")
//            ->whereWeek('created_at')//本周
            ->where($where)->order('created_at','desc')
            ->page($params['page'],$params['limit'])->fetchSql()->select();

        $result =  $warehousingModel->field("warehousing_id as order_id, IF(ISNULL('warehousing_id'),0,'入库') as order_type,created_at,goods_number,project_id,project_client")
            ->union($warehouse_out_sql)
//            ->whereWeek('created_at')//本周
            ->where($where)->order('created_at','desc')
            ->page($params['page'],$params['limit'])->select();

        $result->each(function(&$item, $key){
            $item['project_name'] = Db::table('db_project')->where('project_id',$item['project_id'])->value('project_name')
                . "/" .
                Db::table('db_project')->where('project_id',$item['project_client'])->value('project_name');

            //格式化时间
            $item['format_time'] = date('m-d',strtotime($item['created_at']));
        });

        return CatchResponse::success($result);
    }

    //结算方
    public function get_settlement($project_client_id){
        $settlement = $this->project
            ->alias('pj')
            ->leftJoin('db_provider pr','pj.provider_id = pr.id')
            ->where('pj.project_id',$project_client_id)
            ->field('pr.settlement')->find()
        ;

        return CatchResponse::success($settlement);
    }
}